﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Base;
using Components;
using Core.Base;
using System.Drawing;
using FilteredGridViewControl;
using DataHelper.DataGridViewSummary;
using System.ComponentModel;
using ERP.DAL;
using System.Globalization;
using System.Collections;

namespace Core.Component
{
    public class SGVGridView: DataGridView, ISGVControl
    //public class SGVGridView : DataGridViewSummary, ISGVControl
    {
        public BaseModule module;
        public BaseEntity entity;

        public ContextMenuStrip CtxMenu;
        public ToolStripMenuItem mnuExport;

        public SGVGridView()
            : base()
        {
            this.ContextMenuStrip = new ContextMenuStrip();
            mnuExport = new ToolStripMenuItem("Export");
            this.ContextMenuStrip.Items.Add(mnuExport);
            mnuExport.Click += new EventHandler(mnuExport_Click);
            
            ChangeApperance();

            #region Event Register

            this.DataError += SGVGridView_DataError;
            this.KeyDown += new KeyEventHandler(SGVGridView_KeyDown);
            this.CellEndEdit += new DataGridViewCellEventHandler(SGVGridView_CellEndEdit);
            this.CellBeginEdit += new DataGridViewCellCancelEventHandler(SGVGridView_CellBeginEdit);
            this.CellValueChanged += new DataGridViewCellEventHandler(SGVGridView_CellValueChanged);
            this.RowPrePaint += SGVGridView_RowPrePaint;
            this.LostFocus += SGVGridView_LostFocus;
            this.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(SGVGridView_EditingControlShowing);
            this.CellPainting += new DataGridViewCellPaintingEventHandler(SGVGridView_CellPainting);
            this.CellEnter += SGVGridView_CellEnter;
            this.CellLeave += SGVGridView_CellLeave;
            this.Scroll += new ScrollEventHandler(SGVGridView_Scroll);

            this.CellEnter += new DataGridViewCellEventHandler(SGVGridView_CellEnter);

            this.RowHeaderMouseClick += new DataGridViewCellMouseEventHandler(SGVGridView_RowHeaderMouseClick);

            this.RowValidating += new DataGridViewCellCancelEventHandler(SGVGridView_RowValidating);
            this.CellValidating += new DataGridViewCellValidatingEventHandler(SGVGridView_CellValidating); 
            #endregion

        }

        public Core.Component.UIComponent component
        {
            set;
            get;
        }

        void SGVGridView_Scroll(object sender, ScrollEventArgs e)
        {
            //this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
 
            ////Get the preffered width for displayed data against each column and compare to current width
            ////Set the new column width only if greater than current
            //foreach (DataGridViewColumn column in Columns)
            //{
            //    if (column.GetPreferredWidth(DataGridViewAutoSizeColumnMode.DisplayedCells, true) > column.Width)
            //    {
            //        column.Width = column.GetPreferredWidth(DataGridViewAutoSizeColumnMode.DisplayedCells, true);
            //    }
            //}
            //this.PerformLayout();
        }

        void SGVGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            //Rectangle newRect = new Rectangle(e.CellBounds.X + 1,
            //        e.CellBounds.Y + 1, e.CellBounds.Width - 4,
            //        e.CellBounds.Height - 4);

            //e.Graphics.DrawIcon(new Icon(@"E:\Projects\ERP\MainApp\bin\Debug\Image\Search.ico"), newRect);

            //using (
            //    Brush gridBrush = new SolidBrush(this.GridColor),
            //    backColorBrush = new SolidBrush(e.CellStyle.BackColor))
            //{
            //    using (Pen gridLinePen = new Pen(gridBrush))
            //    {
            //        // Erase the cell.
            //        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

            //        // Draw the grid lines (only the right and bottom lines; 
            //        // DataGridView takes care of the others).
            //        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
            //            e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
            //            e.CellBounds.Bottom - 1);
            //        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
            //            e.CellBounds.Top, e.CellBounds.Right - 1,
            //            e.CellBounds.Bottom);

            //        // Draw the inset highlight box.
            //        e.Graphics.DrawRectangle(Pens.Blue, newRect);
            //        e.Graphics.DrawEllipse(new Pen(Color.Red), newRect);

            //        // Draw the text content of the cell, ignoring alignment. 
            //        if (e.Value != null)
            //        {
            //            e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
            //                Brushes.Crimson, e.CellBounds.X + 2,
            //                e.CellBounds.Y + 2, StringFormat.GenericDefault);
            //        }
            //        e.Handled = true;
            //    }
            //}
        }
        

        protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)
        {
            base.OnRowPostPaint(e);
            String strRowIndex = (e.RowIndex + 1).ToString();
            Font f = new Font("Tahoma", 8.0f, FontStyle.Bold);
            StringFormat strFormat = new StringFormat();
            strFormat.Alignment = StringAlignment.Far;
            strFormat.LineAlignment = StringAlignment.Near;
            Rectangle rec = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, this.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(strRowIndex, f, SystemBrushes.ControlText, rec, strFormat);
        }

        void SGVGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            try
            {
                String strError = module.FieldValidating(Rows[e.RowIndex].DataBoundItem, Columns[e.ColumnIndex].DataPropertyName, e.FormattedValue);
                if (String.IsNullOrEmpty(strError) == false)
                {
                    //Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = strError;
                    Rows[e.RowIndex].ErrorText = strError;
                    this.CurrentCell = Rows[e.RowIndex].Cells[e.ColumnIndex];
                    e.Cancel = true;
                }
                else
                {
                    //Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = String.Empty;
                    Rows[e.RowIndex].ErrorText = String.Empty;

                }
                 
            }
            catch (Exception ex)
            {
            }
        }

        void SGVGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                String strError = module.ObjectValidating(Rows[e.RowIndex].DataBoundItem);
                if (String.IsNullOrEmpty(strError) == false)
                {
                    Rows[e.RowIndex].ErrorText = strError;
                    e.Cancel = true;
                }
                else
                {
                    Rows[e.RowIndex].ErrorText = String.Empty;
                }
            }
            catch (Exception ex)
            {
            }
            
        }

        void SGVGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //this.EndEdit();
        }

        protected override void OnNewRowNeeded(DataGridViewRowEventArgs e)
        {
            base.OnNewRowNeeded(e);

            if (entity.MainObject == null) return;

            if (Columns.Contains(AppContext.cstFKStock))
            {
                Object objStockID = AppContext.GetProperty(entity.MainObject, AppContext.cstFKStock);
                if (objStockID != null)
                {
                    int iStockID = Convert.ToInt32(objStockID);
                    e.Row.Cells[AppContext.cstFKStock].Value = iStockID;
                }
            }
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            //if the key pressed is "return" then tell the datagridview to move to the next cell
            if (keyData == Keys.Enter)
            {
                this.BeginInvoke(new MethodInvoker(delegate() { MoveToNextCell(); }));

                return true;
            }
            else
                return base.ProcessDialogKey(keyData);
        }

        /// <summary>
        /// this function moves the focus to the next cell
        /// </summary>
        public void MoveToNextCell()
        {
            int CurrentColumn, CurrentRow;

            //get the current indicies of the cell
            CurrentColumn = this.CurrentCell.ColumnIndex;
            CurrentRow = this.CurrentCell.RowIndex;

            if (Columns[CurrentColumn] == null || Columns[CurrentColumn] is SGVLookUpColumn)
                return;

            //if cell is at the end move it to the first cell of the next row
            //other with move it to the next cell
            if (CurrentColumn == this.Columns.Count - 1 && CurrentRow != this.Rows.Count - 1)
            {
                base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Home));
                base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Down));
            }
            else
                base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Right));

        }

        void SGVGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.Control.KeyDown += new KeyEventHandler(Control_KeyDown);
        }

        void Control_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                if (SelectedRows.Count == 1)
                {
                    Rows.Remove(SelectedRows[0]);
                }
            }
            if (e.KeyCode == Keys.F2)
            {
                if (sender != null
                    && sender is ComboBox)
                {
                    ComboBox comboBox = sender as ComboBox;
                    comboBox.DroppedDown = !comboBox.DroppedDown;
                }
            }
            if (e.KeyCode == Keys.F4)
                e.Handled = true;
        }

        void mnuExport_Click(object sender, EventArgs e)
        {
            Export();
        }

        void SGVGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            //Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.FromArgb(51,153,255);
        }

        void SGVGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (Columns[e.ColumnIndex] != null)
                {
                    if (Columns[e.ColumnIndex] is DataGridViewComboBoxColumn == false)
                    {
                        if (EditingControl != null
                            && EditingControl is TextBox)
                        {
                            TextBox txtBox = EditingControl as TextBox;
                            txtBox.SelectAll();
                        }
                    }
                   
                }
            }
            catch (Exception ex)
            {
            }
            
            //if (Columns[e.ColumnIndex] != null && Columns[e.ColumnIndex] is DataGridViewComboBoxColumn)// the combobox column index
            //{
            //    if (EditingControl != null
            //        && EditingControl is ComboBox)
            //    {
            //        ComboBox cmb = EditingControl as ComboBox;
            //        cmb.DroppedDown = true;
            //    }
            //}
        }

        void SGVGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            e.PaintParts &= ~DataGridViewPaintParts.Focus;
        }

        void SGVGridView_LostFocus(object sender, EventArgs e)
        {
            
        }

        void SGVGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex == -1) return;
                if (e.ColumnIndex == -1) return;

                if (this.DataSource == null || this.DataSource is ISGVList == false) return;

                Object objItem = ((ISGVList)this.DataSource).GetAt(e.RowIndex);
                if (objItem == null) return;


                if (this.Tag != null && this.Tag.ToString().ToUpper().Equals(AppContext.cstGridViewItems) == false) return;

                //module.InitDefaultItems(objItem);
                String strFieldName = Columns[e.ColumnIndex].DataPropertyName;
                if (String.IsNullOrEmpty(strFieldName)) return;

                module.CalcItem(entity.MainObject, objItem, strFieldName);
            }
            catch (Exception ex)
            {
                
            }
            
        }

        void SGVGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Yellow;
            }
            catch (Exception ex)
            {
            }
            
        }

        void SGVGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            }
            catch (Exception ex)
            {
            }
            
////            if (e.ColumnIndex >= 0 && this.Columns[e.ColumnIndex] is SGVNumberTextBoxColumn)
//            if (e.ColumnIndex >= 0 && this.Columns[e.ColumnIndex].ValueType == typeof(double))
//            {
//                String strText = this.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString();

//                //this.Rows[e.RowIndex].Cells[e.ColumnIndex].Te = AppContext.ConvertStringToNumber(strText);
//            }
        }

        void SGVGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
        }

        public void ChangeApperance()
        {
            this.MultiSelect = false;
            this.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.EnableHeadersVisualStyles = true;
            this.RowHeadersVisible = true;
            this.EditMode = DataGridViewEditMode.EditOnEnter;
            this.VirtualMode = true;
            this.AllowUserToResizeColumns = true;
            this.CellBorderStyle = DataGridViewCellBorderStyle.Single;
            this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            this.EditMode = DataGridViewEditMode.EditOnEnter;
            this.ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.False;
            this.ColumnHeadersHeight = 30;
            //this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            //this.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(1, 121, 254);
            this.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(32, 85, 135);
            this.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            //this.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //this.ColumnHeadersDefaultCellStyle.Font = new Font(this.ColumnHeadersDefaultCellStyle.Font.FontFamily, 8, FontStyle.);
        }

        void SGVGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.SelectedRows.Count > 0 && this.SelectedRows[0].IsNewRow == false)
                    this.Rows.Remove(this.SelectedRows[0]);
            }

            
        }

        public void RegisterModule(Base.BaseModule _module)
        {
            if (_module != null)
            {
                module = _module;
                entity = _module.entity;
            }
        }

        public void Init()
        {
            this.ShowCellErrors = true;
            
            ChangeApperance();

            InitColumns();

            if (this.Tag != null && this.Tag.ToString() == AppContext.cstGridViewItems)
                module.ItemGridView = this;
        }

        public virtual void InitColumns()
        {
            foreach (DataGridViewColumn col in Columns)
            {
                if (col is ISGVControl)
                {
                    ((ISGVControl)col).Init();
                    //col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    //col.Resizable = DataGridViewTriState.True ;
                }
            }
        }

        public void InitCellStyles()
        {
            foreach (DataGridViewColumn col in this.Columns)
            {
                if(col is IBindingControl == false) continue;
                IBindingControl bindingCol = (IBindingControl)col;

                DataGridViewCellStyle stl = new DataGridViewCellStyle();
                if (col is SGVTextBoxColumn && (col.ValueType == typeof(double) || col.ValueType == typeof(int)))
                {
                    stl.Alignment = DataGridViewContentAlignment.MiddleRight;
                    stl.Format = AppContext.GetNumericFormat();
                }
                else
                {
                    stl.Alignment = DataGridViewContentAlignment.MiddleLeft;
                }
                col.DefaultCellStyle = stl;
            }
        }
        String _sGVShortcutString;
        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public String SGVShortcutString
        {
            get { return _sGVShortcutString; }
            set { _sGVShortcutString = value; }
        }
        String _sGVTag;
        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string SGVTag
        {
            get
            {
                return _sGVTag;
            }
            set
            {
                _sGVTag = value;
            }
        }

        public void UpdateFormat()
        {
        }

        public void Export()
        {
           // System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

           // Microsoft.Office.Interop.Excel._Application app  = new Microsoft.Office.Interop.Excel.Application();
 
 
           // // creating new WorkBook within Excel application
           // Microsoft.Office.Interop.Excel._Workbook workbook =  app.Workbooks.Add(Type.Missing);
           
 
           // // creating new Excelsheet in workbook
           //  Microsoft.Office.Interop.Excel._Worksheet worksheet = null;                   
           
           //// see the excel sheet behind the program
           // app.Visible = true;
          
           //// get the reference of first sheet. By default its name is Sheet1.
           //// store its reference to worksheet
           // worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets["Sheet1"];
           //// worksheet = workbook.ActiveSheet;
           // // changing the name of active sheet
           // worksheet.Name = "Exported from gridview";
 
           
           // // storing header part in Excel
           // for(int i=1; i<Columns.Count+1;i++)
           // {
           //     worksheet.Cells[1, i] = Columns[i-1].HeaderText;
           // }
 
 
 
           // // storing Each row and column value to excel sheet
           // for (int i=0; i < Rows.Count-1 ; i++)
           // {
           //     for(int j=0;j< Columns.Count;j++)
           //     {
           //         if (Rows[i].Cells[j].Value != null)
           //             worksheet.Cells[i + 2, j + 1] = Rows[i].Cells[j].Value.ToString();
           //     }
           // }
 
 
           // // save the application
           // workbook.SaveAs("c:\\output.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing);
           
           // // Exit from the application
           // app.Quit();
        }

        public UIComponent Serialize()
        {
            UIComponent component = new UIComponent();
            SGVControlHelper.CreateUIComponentFromControl(component, this);

            if (component != null)
            {
                component.Value = this.Text;
                foreach (DataGridViewColumn col in this.Columns)
                {
                    if (col is ISGVControl)
                    {
                        UIComponent childComponent = ((ISGVControl)col).Serialize();
                        if (childComponent != null)
                            component.lstChilds.Add(childComponent);
                    }
                }
            }
            return component;
        }

        public void Deserialize(UIComponent component)
        {
            throw new NotImplementedException();
        }
    }
}
